package com.baiwei.vpnapi.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baiwei.vpnapi.dao.*;
import com.baiwei.vpnapi.entity.*;
import com.baiwei.vpnapi.entity.respentity.AvailablePackage;
import com.baiwei.vpnapi.service.AppService;
import com.baiwei.vpnapi.service.VpnService;
import com.baiwei.vpnapi.utils.AppUtils;
import com.baiwei.vpnapi.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: vpnapi
 * @description: app服务实现类
 * @author: Mr. Stone
 * @create: 2020-03-11 00:16
 **/

@Service
public class AppServiceImpl implements AppService {
    @Autowired
    private PaymethodMapper paymethodMapper;

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private VpnMessageMapper vpnMessageMapper;

    @Autowired
    private DeviceTokenMapper deviceTokenMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPackageMapper userPackageMapper;

    @Autowired
    private VpnAdvertMapper vpnAdvertMapper;

    @Value("${newApiVersion}")
    private String newApiVersion;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object macOnline() {
        String platform = request.getHeader("platform");
        String version = request.getHeader("version");
        if(!StringUtils.equals(newApiVersion, version)) {
            return "0";
        }
        if(platform.equals("4")) {
            if(stringRedisTemplate.hasKey("macos")) {
                return "1";
            } else {
                return "0";
            }
        } else {
            if(stringRedisTemplate.hasKey("iphoneos")) {
                return "1";
            } else {
                return "0";
            }
        }
    }

    @Override
    public Object getAdvertisements() {
        String token = request.getHeader("Authorization");
        Integer userType = null;
        if(StringUtils.isEmpty(token)) {
            userType = 0;
        } else {
            VpnUser user =  jwtTokenUtil.getVpnUser(token);
            List<AvailablePackage> exclusivePackage = userPackageMapper.findExclusivePackage(user.getUserId());
            AvailablePackage currentPakcage = userPackageMapper.findCurrentPakcage(user.getUserId());
            if(exclusivePackage != null && exclusivePackage.size() != 0) {
                userType = 2;
            } else if(currentPakcage != null) {
                userType = 1;
            } else {
                userType = 0;
            }
        }

        VpnAdvert launchAd = vpnAdvertMapper.getLaunchAdvert(String.valueOf(userType));
        List<VpnAdvert> banners = vpnAdvertMapper.getBannerAdverts(String.valueOf(userType));
        VpnAdvert alertAd = vpnAdvertMapper.getAlertAdvert(String.valueOf(userType));
        Map<String, Object> res = new HashMap<>();
        res.put("banner", banners);
        res.put("launch", launchAd);
        res.put("alert", alertAd);
//        if(lang.equals("1") && ads != null) {
//            for(VpnAdvert ad: ads) {
//                ad.setTitle(ad.getEnglishTitle());
//                ad.setContent(ad.getEnglishContent());
//            }
//        } else if(lang.equals("2") && ads != null) {
//            for(VpnAdvert ad: ads) {
//                ad.setTitle(ad.getTwTitle());
//                ad.setContent(ad.getTwContent());
//            }
//        }
        return res;
    }

    @Override
    public Object getVersionInfo() {
        return null;
    }

    @Override
    public Object getAppConfig() {
        String platform = request.getHeader("platform");
        String lang = request.getHeader("language");
        String token = request.getHeader("Authorization");
        VpnUser user =  jwtTokenUtil.getVpnUser(token);



        String ipAddr = AppUtils.getIpAddr(request);
        user.setLoginPlatform(request.getHeader("platform"));

        user.setLoginVersion(request.getHeader("version"));
        user.setLoginIp(ipAddr);
        userMapper.updateById(user);

        Map<String, Object> info = new HashMap<>();
        AppVersion version = appVersionMapper.getCurrentVersion(platform);
        if(lang.equals("1") && version != null) {
            version.setVersionDesc(version.getVersionDescEn());
        } else if(lang.equals("2") && version != null) {
            version.setVersionDesc(version.getVersionDescTw());
        }
        info.put("version", version);
        if(!user.getUsername().equals("pony1234@126.com")) {
            List<VpnPaymethod> methods = paymethodMapper.getAvailablePaymethod(platform);
            if(methods != null && methods.size() > 0) {
                for(VpnPaymethod method: methods) {
                    if(lang.equals("1")) {
                        method.setPaymentName(method.getEnglishName());
                    } else if(lang.equals("2")) {
                        method.setPaymentName(method.getTaiwanName());
                    }
                }
            }
            info.put("payMethod", methods);
        } else {
            info.put("payMethod", null);
        }

        return info;
    }

    @Override
    public Object getMessage(Integer pageNo, Integer pageSize) {
        List<VpnMessage> msgs = vpnMessageMapper.getMessage(pageNo, pageSize);
        Map<String, Object> res = new HashMap<>();
        res.put("pageNo", pageNo);
        res.put("pageSize", pageSize);
        res.put("data", msgs);
        return res;
    }

    public Object uploadIosToken(String deviceToken) {
        String userToken = request.getHeader("Authorization");
        IosDeviceToken qtoken = new IosDeviceToken();
        qtoken.setTokenIdentify(deviceToken);
        IosDeviceToken rtoken = deviceTokenMapper.selectOne(new QueryWrapper<>(qtoken));
        if(rtoken == null) {
            if(userToken != null && userToken.length() > 0) {
                String userId = jwtTokenUtil.getUsernameFromToken(userToken);
                qtoken.setUserId(new Integer(userId));
            }
            deviceTokenMapper.insert(qtoken);
        } else {
            if(userToken != null && userToken.length() > 0) {
                String userId = jwtTokenUtil.getUsernameFromToken(userToken);
                rtoken.setUserId(new Integer(userId));
            }
            deviceTokenMapper.updateById(rtoken);
        }
        return "success";
    }

}
